package com.education.cms.filter;

import com.education.cms.utils.RedisUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter")
public class LoginFilter implements Filter {
    private String ignoreURL;
    private RedisUtils redisUtils;

    public LoginFilter(RedisUtils redisUtils){
        this.redisUtils=redisUtils;
    }

    public void init(FilterConfig config) throws ServletException {
        ignoreURL=config.getInitParameter("ignoreURL");
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        if (request.getServletPath().equals(ignoreURL)){
            chain.doFilter(req,resp);
        }else {
            String ticket = (String) request.getSession().getAttribute("loginfo");
            request.setAttribute("ticket",ticket);
            if (ticket != null && !ticket.isEmpty() && redisUtils.isExist(ticket)){
                redisUtils.getAndSet(ticket,redisUtils.get(ticket));  //每次登录校验完成后都要刷新一次redis中的数据，为求与session保持一致
                chain.doFilter(req,resp);
            } else if (ticket == null || ticket.isEmpty()){
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("您还未登录！");
            } else if (!redisUtils.isExist(ticket)){
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println("登录校验未通过，请重新登录！！");
            }
        }
    }


    public void destroy() {
    }

}
